from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import time
import datetime
import json


def get_data(device_name, product_key, identifier):
    accessKeyId = 'LTAI4GAhaCeHUhgYni41W6o3'
    accessSecret = 'MfYU5oT9rdVZptcdqSnZ4DZJsJloYI'

    client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')

    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('iot.cn-shanghai.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https') # https | http
    request.set_version('2018-01-20')
    request.set_action_name('QueryDevicePropertyData')

    end_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    start_date = (datetime.datetime.now() - datetime.timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S")
    start_time = int(round(time.mktime(time.strptime(start_date, "%Y-%m-%d %H:%M:%S"))) * 1000)
    end_time = int(round(time.mktime(time.strptime(end_date, "%Y-%m-%d %H:%M:%S"))) * 1000)

    request.add_query_param('RegionId', "cn-hangzhou")
    request.add_query_param('StartTime', start_time)
    request.add_query_param('Identifier', identifier)
    request.add_query_param('Asc', 0)
    request.add_query_param('EndTime', end_time)
    request.add_query_param('PageSize', 50)
    request.add_query_param('ProductKey', product_key)
    request.add_query_param('DeviceName', device_name)

    response = client.do_action_with_exception(request)
    response_data = json.loads(str(response, encoding='utf-8'))
    data = response_data["Data"]["List"]["PropertyInfo"][::-1]

    rtn_data = list()
    for i, a_data in enumerate(data):
        a_rtn_data = dict()
        a_rtn_data['id'] = i
        for key, value in a_data.items():
            if key == 'Value':
                a_rtn_data['value'] = value
            else:
                a_rtn_data['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(value / 1000))
        rtn_data.append(a_rtn_data)

    return rtn_data


if __name__ == '__main__':
    data = get_data('Voltage', 'a1hhc8u1lHd', 'Voltage')
    print(data)

